package com.pudu.pudusclient;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Base64;
import android.util.Log;

import com.pudu.mydemo.utils.RobotFileUtils;
import com.pudu.pdrobot.App;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;

/**
 * Created by fanyp on 2016/10/18.
 *
 * 暂时支持imagelist类型，如果itme不设置位置和缩放，默认铺满整个屏幕
 *
 */
public class CustomTemplate {

    static CustomTemplate mInstance;

    public ArrayList<TemplateItem> TemplateItems;

    public String mstrJsonSource;

    public int mCurrentTemplateID = 0;

    private CustomTemplate(){}

    public static CustomTemplate getInstance()
    {
        if(mInstance == null)
        {
            mInstance = new CustomTemplate();
        }

        return mInstance;
    }

    public void initData(){
        Context mContext = App.getInstance();
        if( mContext == null) {
            return;
        }

        TemplateItems = new ArrayList<TemplateItem>();

        try {
            InputStream is = mContext.getAssets().open("template.json");
            int size = is.available();

            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            String text = new String(buffer, "UTF-8");
            mstrJsonSource = text;
            Log.i("eeee", text);

            JSONObject myobj = new JSONObject(text);
            JSONArray myTemplateItems= myobj.getJSONArray("template");

            for(int i = 0; i < myTemplateItems.length(); i ++)
            {
                JSONObject objTemplateItem = myTemplateItems.getJSONObject(i);

                TemplateItem item = new TemplateItem();
                item.id = objTemplateItem.getString("id");
                item.diagram = objTemplateItem.getString("diagram");
                item.name = objTemplateItem.getString("name");

                item.contents = new ArrayList<TemplateContentItem>();

                JSONArray myTemplateContentItems = objTemplateItem.getJSONArray("content");
                for(int j = 0; j < myTemplateContentItems.length(); j ++)
                {
                    JSONObject objTemplateContentItem = myTemplateContentItems.getJSONObject(j);

                    TemplateContentItem ContentItem = new TemplateContentItem();
                    ContentItem.type = objTemplateContentItem.getString("type");
                    //不同的类型需要进行不同解析
                    if(ContentItem.type.compareTo("imagelist") == 0)
                    {
                        ContentItem.number = objTemplateContentItem.getString("number");
                        JSONArray subTemplateContentItems = objTemplateContentItem.getJSONArray("items");

                        if(ContentItem.subItems == null)
                        {
                            ContentItem.subItems = new ArrayList<TemplateContentItem>();
                        }

                        for(int k = 0; k < subTemplateContentItems.length(); k ++)
                        {
                            JSONObject subTemplateContentItem = subTemplateContentItems.getJSONObject(k);

                            TemplateContentItem subContentItem = new TemplateContentItem();
                            subContentItem.id = subTemplateContentItem.getString("id");
                            subContentItem.type = subTemplateContentItem.getString("type");
                            ContentItem.subItems.add(subContentItem);
                        }
                    }

                    item.contents.add(ContentItem);

                }

                TemplateItems.add(item);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        initCurrentTemplateID();

        initSDFileDir();
    }

    public void initSDFileDir(){

        RobotFileUtils.buildDir("/sdcard/PuduRobotTemplate");
        for(int i = 0; i < TemplateItems.size(); i ++)
        {
            TemplateItem obj = TemplateItems.get(i);
            String strDir = "/sdcard/PuduRobotTemplate" + File.separator
                    + obj.id;
            RobotFileUtils.buildDir(strDir);
        }
    }

    public void initCurrentTemplateID()
    {
        Context mContext = App.getInstance();
        if( mContext == null)
        {
            return;
        }

        try {
            SharedPreferences mSharedPreferences = mContext.getSharedPreferences("TEMPLATE_CUSTOM", 0);

            mCurrentTemplateID = mSharedPreferences.getInt("TEMPLATE_CURRENT_ID", 0);

            if (mCurrentTemplateID >= TemplateItems.size()) {
                mCurrentTemplateID = TemplateItems.size() - 1;
                SharedPreferences.Editor mEditor = mSharedPreferences.edit();
                mEditor.putInt("TEMPLATE_CURRENT_ID", mCurrentTemplateID);
                mEditor.commit();
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    public String BuildTemplateData()
    {
        try {
            String data = "";

            if (TemplateItems.size() <= 0) {
                return BuildErrorTemplateData();
            }

            if( mstrJsonSource == null || mstrJsonSource.isEmpty() == true) {
                return BuildErrorTemplateData();
            }

            JSONObject myObjectSource = new JSONObject(mstrJsonSource);
            JSONArray templateitems = myObjectSource.getJSONArray("template");

            JSONObject myObject = new JSONObject();
            JSONArray newTemplatitems = new JSONArray();

            for(int i = 0; i < templateitems.length(); i ++)
            {
                JSONObject myItemObj = templateitems.getJSONObject(i);

                JSONObject mynewObject = new JSONObject();

                mynewObject.put("id", myItemObj.getString("id"));
                mynewObject.put("name", myItemObj.getString("name"));
                mynewObject.put("content", myItemObj.getJSONArray("content"));

                byte[] data_diagram = GetAssetsFileByName(myItemObj.getString("diagram"));
                String str_diagram = Base64.encodeToString(data_diagram, Base64.DEFAULT);

                mynewObject.put("diagram", str_diagram);

                newTemplatitems.put(mynewObject);
            }

            myObject.put("template",newTemplatitems);

            return myObject.toString();
        }catch(Exception e)
        {
            e.printStackTrace();
        }

        return BuildErrorTemplateData();
    }

    public byte[] GetAssetsFileByName(String fileName)
    {
        Context mContext = App.getInstance();
        byte[] buffer = null;

        try {
            InputStream is = mContext.getAssets().open(fileName);
            int size = is.available();

            buffer = new byte[size];
            is.read(buffer);
            is.close();
        }catch(Exception e)
        {
            e.printStackTrace();
        }

        return buffer;
    }

    public String BuildErrorTemplateData()
    {
        String data = "{\"type\":\"error\",\"content\":\"unkown\"";
        return data;
    }

    public static class TemplateItem{
        public TemplateItem(){}

        public String name;
        public String diagram;
        public String id;

        public ArrayList<TemplateContentItem> contents;
    }

    public static class TemplateContentItem{
        public TemplateContentItem(){}

        public String type;
        public String id;
        public String number;
        public ArrayList<TemplateContentItem> subItems;
    }

}
